package com.example.project.projectspringcloud.intercepter;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.entity.user.Menu;
import com.example.project.projectspringcloud.service.user.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 网站配置管理拦截器
 *
 * @date 2018-08-31 11:57
 * @author Christopher Jones
 */
@Component
public class ProjectIntercepter implements HandlerInterceptor {

    @Autowired
    private PermissionService permissionService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<Menu> menus = permissionService.selectAllMenuByRole(false);
        request.setAttribute("menus", menus);

        // web环境参数
        request.setAttribute("ctx", Constants.contextPath = "http://" + request.getServerName() + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : ""));
        request.setAttribute("staticServer", Constants.staticServer);
        request.setAttribute("uploadServer", Constants.uploadServer);
        request.setAttribute("mydomain", Constants.MYDOMAIN);
        return true;
    }
}
